package com.xyh.reward_kotlin.intercept

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.nio.charset.StandardCharsets
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import android.util.Base64

class SecureInterceptor(
    private val appId: String,
    private val secret: String
) : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val timestamp = System.currentTimeMillis().toString()

        val signature = try {
            hmacSHA256(appId + timestamp, secret)
        } catch (e: Exception) {
            throw IOException("签名生成失败", e)
        }

        val newRequest: Request = chain.request().newBuilder()
            .addHeader("X-App-Id", appId)
            .addHeader("X-Timestamp", timestamp)
            .addHeader("X-Signature", signature)
            .build()

        return chain.proceed(newRequest)
    }

    @Throws(Exception::class)
    private fun hmacSHA256(data: String, secret: String): String {
        val sha256Hmac = Mac.getInstance("HmacSHA256")
        val secretKey = SecretKeySpec(secret.toByteArray(StandardCharsets.UTF_8), "HmacSHA256")
        sha256Hmac.init(secretKey)
        val hash = sha256Hmac.doFinal(data.toByteArray(StandardCharsets.UTF_8))
        // Android Base64 (NO_WRAP 去掉换行符)
        return Base64.encodeToString(hash, Base64.NO_WRAP)
    }
}
